#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <string>
#include <iostream>
#include <sstream>

#include <arpa/inet.h>

/**
 * @author Kristina Kurian
 * @usage: client <IP> <Message>
 * @date: 03-10-2011
*/

#define BUFFER 1024
#define SERV_PORT 9877

std::string convertInt(int number) {
   std::stringstream ss;
   ss << number;
   return ss.str();
}

class SerializableObject {
	public:
		virtual int getIdentifier() = 0;
	    	virtual std::string serialize(char *t) = 0;
};

class SubclassA : public SerializableObject {
	public:	
    		int getIdentifier() { return 1; }
    		std::string serialize(char *t) { 
			return convertInt(getIdentifier()) + ":" + convertInt(std::string(t).length())  + ":" + std::string(t);
		}
};

class SubclassB : public SerializableObject {
	public:	
    		int getIdentifier() { return 2; }
    		std::string serialize(char *t) {
			return convertInt(getIdentifier()) + ":" + convertInt(std::string(t).length())  + ":" + std::string(t);		
		}
};

class SubclassC : public SerializableObject {
	public:	
    		int getIdentifier() { return 3; }
    		std::string serialize(char *t) { 
			return convertInt(getIdentifier()) + ":" + convertInt(std::string(t).length())  + ":" + std::string(t);		
		}

		void execute() { 
			std::cout << "SubclassC" << std::endl;
		}
};

int main(int argc, char **argv) {
	int sock;
	char send_buf[BUFFER];
	struct sockaddr_in addr;

	
	if (argc != 5) {
		printf("ERROR: Wrong initial parametr!\n");
		return 1;
	}
	
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock == -1) {
		printf("ERROR: Could not create socket\n");
		return 1;
	}
	
	bzero(&addr, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(SERV_PORT);
	addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
		
	inet_aton(argv[1], (struct in_addr*)&addr.sin_addr.s_addr);
	
	SubclassA a;
	std::string ser_string = a.serialize(argv[2]);
	memcpy(send_buf, (void *)ser_string.c_str(), strlen(ser_string.c_str()));
	sendto(sock, (void *)send_buf, sizeof(send_buf), 0, (struct sockaddr *)&addr, (socklen_t)sizeof(addr));

	SubclassB b;
	ser_string = b.serialize(argv[3]);
	
	memcpy(send_buf, ser_string.c_str(), ser_string.length());
	sendto(sock, (void *)send_buf, sizeof(send_buf), 0, (struct sockaddr *)&addr, (socklen_t)sizeof(addr));

	SubclassC c;
	ser_string = c.serialize(argv[4]);
	
	memcpy(send_buf, ser_string.c_str(), ser_string.length());
	sendto(sock, (void *)send_buf, sizeof(send_buf), 0, (struct sockaddr *)&addr, (socklen_t)sizeof(addr));

	close(sock);
	return 0;
}
